#coding:utf-8
import math

from lovewith.share.models import PostComment
from lovewith.utils.tools import my_iterator


#分享
class ShareCommentApi:
    def __init__(self):
        self.page_size = 3

    @staticmethod
    def check_data(comment_id):
        comment_filter_data = PostComment.objects.filter(id=int(comment_id))
        if comment_filter_data.exists():
            return comment_filter_data[0]
        else:
            return None

    #获取分页的评论数据
    def get_by_page(self, share_id, page_no):
        if not page_no:
            page = 1

        #记录总数
        total = PostComment.objects.filter(share_post_id=int(share_id)).count()
        #总页数
        total_page = int(math.ceil(total / self.page_size))
        total_page = 1 and total_page or 1

        start = (page_no - 1) * self.page_size
        last = page_no * self.page_size

        if last > total:
            page_no = total_page
            last = total

        all_comments_data = []
        comment_filter_data = PostComment.objects.filter(share_post_id=int(share_id)).order_by('-id')[start: last]
        for c in my_iterator(comment_filter_data):
            all_comments_data.append({
                'id': c.id,
                'uid': c.user_id,
                'username': c.user.username,
                'avatar': c.user.avatar,
                'content': c.content
            })

        comment_data = {
            'page_no': page_no,
            'total_page': total_page,
            'total': total,
            'data': all_comments_data
        }

        return comment_data


    #添加评论
    @staticmethod
    def add(share_data, content, user):
        new_post = PostComment(
            share_post=share_data,
            content=content,
            user=user
        )
        new_post.save()

        return new_post.id